package com.cloud.wms.ui.main.fragment;

import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.eventBus.Event;
import com.cloud.core.utils.NumberUtils;
import com.cloud.widget.expand.ExpandLayout;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseViewPagerFragment;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.config.TaskCode;
import com.cloud.wms.ui.group.collect.GroupCollectActivity;
import com.cloud.wms.ui.group.obtain.ObtainInventoryActivity;
import com.cloud.wms.ui.group.obtain.ObtainScanContainerActivity;
import com.cloud.wms.ui.group.sampling.SamplingOrderActivity;
import com.cloud.wms.ui.in.activity.InOrderDetailActivity;
import com.cloud.wms.ui.in.register.InRegisterActivity;
import com.cloud.wms.ui.inside.replenish.ReplenishDownBindActivity;
import com.cloud.wms.ui.inside.replenish.ReplenishTaskDetailActivity;
import com.cloud.wms.ui.inside.replenish.ReplenishUpCheckActivity;
import com.cloud.wms.ui.main.activity.TaskSearchActivity;
import com.cloud.wms.ui.main.adapter.MineTaskAdapter;
import com.cloud.wms.ui.main.contract.MainContract;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.ui.main.entity.TaskMemberEntity;
import com.cloud.wms.ui.main.entity.TaskMenuEntity;
import com.cloud.wms.ui.main.presnter.MainPresenter;
import com.cloud.wms.ui.sort.BatchActivity;
import com.cloud.wms.ui.sort.car.CarTypeActivity;
import com.cloud.wms.ui.sort.group.GroupBindActivity;
import com.cloud.wms.ui.sort.order.OrderBindActivity;
import com.cloud.wms.ui.sort.sku.SkuBindActivity;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.trello.rxlifecycle3.LifecycleTransformer;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import dagger.BindsOptionalOf;

public class MineTaskFragment extends BaseViewPagerFragment<MainPresenter> implements MainContract.View {
    @BindView(R.id.expand_layout)
    ExpandLayout expandLayout;
    @BindView(R.id.rv_task_menu)
    RecyclerView rvTaskMenu;
    @BindView(R.id.rv_task)
    RecyclerView rvTask;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private BaseQuickAdapter<TaskMenuEntity, BaseViewHolder> mTaskMenuAdapter;
    private MineTaskAdapter mMineTaskAdapter;
    private int menuIndex = 0;

    @Override
    protected int getResId() {
        return R.layout.fragment_main_mine_task;
    }

    @Override
    protected void setupComponent() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initEvent(Bundle bundle) {
        Bundle arguments = getArguments();
        ArrayList<TaskMenuEntity> taskMenu = arguments.getParcelableArrayList("TaskMenu");

        rvTaskMenu.setLayoutManager(new LinearLayoutManager(getContext()));
        mTaskMenuAdapter = new BaseQuickAdapter<TaskMenuEntity, BaseViewHolder>(R.layout.item_main_task_menu) {
            @Override
            protected void convert(BaseViewHolder helper, TaskMenuEntity item) {
                helper.setText(R.id.tv_menu_name, item.getTaskName());
                if (menuIndex == helper.getAdapterPosition()) {
                    helper.setTextColor(R.id.tv_menu_name, ContextCompat.getColor(getContext(), R.color.font_blue));
                    helper.setBackgroundResource(R.id.ll_task_menu, R.drawable.bg_task_menu);
                } else {
                    helper.setTextColor(R.id.tv_menu_name, ContextCompat.getColor(getContext(), R.color.font_black));
                    helper.setBackgroundResource(R.id.ll_task_menu, R.drawable.bg_base_info_normal);
                }
            }
        };
        mTaskMenuAdapter.setOnItemClickListener((adapter, view, position) -> {
            menuIndex = position;
            mTaskMenuAdapter.notifyDataSetChanged();
            mPresenter.loadMineTask(mTaskMenuAdapter.getItem(position).getTaskCode());
            if (getTaskCode().equalsIgnoreCase(TaskCode.CODE_003001)
                    || getTaskCode().equalsIgnoreCase(TaskCode.CODE_002002)
                    || getTaskCode().equalsIgnoreCase(TaskCode.CODE_002003)
                    || getTaskCode().equalsIgnoreCase(TaskCode.CODE_002004)
                    || getTaskCode().equalsIgnoreCase(TaskCode.CODE_002005)) {
                if (mMineTaskAdapter.getHeaderLayoutCount() == 0) {
                    mMineTaskAdapter.addHeaderView(getHeaderView());
                }
            } else {
                mMineTaskAdapter.removeAllHeaderView();
            }
            mMineTaskAdapter.notifyDataSetChanged();
        });
        rvTaskMenu.setItemAnimator(new DefaultItemAnimator());
        rvTaskMenu.setAdapter(mTaskMenuAdapter);
        mTaskMenuAdapter.setNewInstance(taskMenu);

        rvTask.setLayoutManager(new LinearLayoutManager(getContext()));
        mMineTaskAdapter = new MineTaskAdapter();
        mMineTaskAdapter.addChildClickViewIds(R.id.tv_task_detail, R.id.btn_task_refuse, R.id.btn_task_execute);
        mMineTaskAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            TaskEntity entity = (TaskEntity) adapter.getData().get(position);
            switch (view.getId()) {
                case R.id.tv_task_detail:
                    switch (entity.getTaskCode()) {
                        case TaskCode.CODE_001001://登记
                        case TaskCode.CODE_001002://清点
                        case TaskCode.CODE_001003://上架
                            InOrderDetailActivity.start(getContext(), entity);
                            break;
                        case TaskCode.CODE_002002://团购备货
                        case TaskCode.CODE_002003://团购集货
                        case TaskCode.CODE_002004://团购绑定流水线
                        case TaskCode.CODE_002005://团购抽检
                        case TaskCode.CODE_003001://1:散单 2:单SKU 3:笼车
                            BatchActivity.start(getContext(), entity);
                            break;
                        case TaskCode.CODE_009001:
                        case TaskCode.CODE_009002:
                            ReplenishTaskDetailActivity.start(getContext(), entity);
                            break;
                    }
                    break;
                case R.id.btn_task_refuse:
                    mPresenter.refuseTask(entity);
                    break;
                case R.id.btn_task_execute:
                    // 订单拣选
                    if (entity.isOrderSort())
                        mPresenter.executeOrderTask(entity);
                    else
                        mPresenter.executeTask(entity);
                    break;
            }
        });
        rvTask.setAdapter(mMineTaskAdapter);

        if (taskMenu != null && !taskMenu.isEmpty()) {
            mPresenter.loadMineTask(taskMenu.get(menuIndex).getTaskCode());
        } else {
            info("当前任务菜单暂无数据");
        }

        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);

        refreshLayout.setOnRefreshListener(refreshLayout -> mPresenter.loadMineTask(taskMenu.get(menuIndex).getTaskCode()));
    }

    public String getTaskCode() {
        return mTaskMenuAdapter.getData().get(menuIndex).getTaskCode();
    }

    @Override
    protected void initData() {

    }

    private View getHeaderView() {
        View header = getLayoutInflater().inflate(R.layout.layout_task_search, rvTask, false);
        View btnTaskSearch = header.findViewById(R.id.btn_task_search);
        btnTaskSearch.setOnClickListener(v -> TaskSearchActivity.start(getContext(), getTaskCode(), false));
        return header;
    }

    private View getEmptyDataView() {
        View notDataView = getLayoutInflater().inflate(com.cloud.core.R.layout.layout_empty, rvTask, false);
        notDataView.setOnClickListener(v -> mPresenter.loadMineTask(mTaskMenuAdapter.getItem(menuIndex).getTaskCode()));
        return notDataView;
    }

    private View getErrorView() {
        View errorView = getLayoutInflater().inflate(com.cloud.core.R.layout.layout_error, rvTask, false);
        errorView.setOnClickListener(v -> mPresenter.loadMineTask(mTaskMenuAdapter.getItem(menuIndex).getTaskCode()));
        return errorView;
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case MainPresenter.TASK_MINE:
                refreshLayout.finishRefresh();
                refreshLayout.resetNoMoreData();//恢复上拉状态
                List<TaskMemberEntity> entities = (List<TaskMemberEntity>) message.obj;
                if (entities.isEmpty()) mMineTaskAdapter.setEmptyView(getEmptyDataView());
                mMineTaskAdapter.setList(entities);
                break;
            case MainPresenter.TASK_WAIT_ERROR:
                refreshLayout.finishRefresh();
                refreshLayout.resetNoMoreData();//恢复上拉状态
                mMineTaskAdapter.setEmptyView(getErrorView());
                break;
            case MainPresenter.TASK_REFUSE:
                success("任务拒绝成功！");
                mPresenter.loadMineTask(mTaskMenuAdapter.getData().get(menuIndex).getTaskCode());
                break;
            case MainPresenter.TASK_EXECUTE:
                TaskEntity taskEntity = (TaskEntity) message.obj;
                switch (taskEntity.getTaskCode()) {
                    case TaskCode
                            .CODE_001001://登记
                        InRegisterActivity.start(getActivity(), taskEntity, null);
                        break;
                    case TaskCode
                            .CODE_001002://清点
                        com.cloud.wms.ui.in.inventory.InTypeActivity.start(getActivity(), taskEntity, null);
                        break;
                    case TaskCode
                            .CODE_001003://上架
                        com.cloud.wms.ui.in.shelf.InTypeActivity.start(getActivity(), taskEntity, null);
                        break;
                    case TaskCode
                            .CODE_002002://团购备货
                        GroupBindActivity.start(getActivity(), false, taskEntity);
                        break;
                    case TaskCode
                            .CODE_002003://团购集货
                        GroupCollectActivity.start(getActivity(), null, taskEntity);
                        break;
                    case TaskCode
                            .CODE_002004://团购绑定流水线
                        ObtainScanContainerActivity.start(getActivity(), taskEntity, 0);
                        break;
                    case TaskCode
                            .CODE_002005://团购抽检
                        SamplingOrderActivity.start(getActivity(), taskEntity, null);
                        break;
                    case TaskCode.CODE_003001://1:散单 2:单SKU 3:笼车
                        switch (taskEntity.getWaveType()) {
                            case 1:
                                OrderBindActivity.start(getActivity(), taskEntity, false);
                                break;
                            case 2:
                                SkuBindActivity.start(getActivity(), taskEntity, false);
                                break;
                            case 3:
                                CarTypeActivity.start(getActivity(), taskEntity);
                                break;
                        }
                        break;
                    case TaskCode
                            .CODE_009001://补货下架
                        ReplenishDownBindActivity.start(getContext(), taskEntity);
                        break;
                    case TaskCode
                            .CODE_009002://补货上架
                        ReplenishUpCheckActivity.start(getContext(), taskEntity);
                        break;
                }
                break;
        }
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventCome(Event event) {
        if (event == null) {
            return;
        }
        switch (event.getCode()) {
            case EventConfig.TASK_REFRESH:
                mPresenter.loadMineTask(mTaskMenuAdapter.getData().get(menuIndex).getTaskCode());
                break;
        }
    }

    @Override
    public <R> LifecycleTransformer<R> toLifecycle() {
        return bindToLifecycle();
    }
}